package com.wingsfrog.puzzle.util;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;

import org.apache.log4j.Logger;

public class ImageUtil {
    private static Logger logger = Logger.getLogger(ImageUtil.class);
    public static int cutImage(File imgFile, int cutNumber, String fileName){
        try{
            BufferedImage source=ImageIO.read(imgFile);
            int allWidth=source.getWidth();
            int allHeight=source.getHeight();
            int width=(int) (allWidth*1.0/cutNumber);
            File path=new File("/tmp/puzzle");
            if(!path.exists()){
                path.mkdirs();
            }
            int height=(int) (allHeight*1.0/cutNumber);
            for(int i=0;i<cutNumber;++i){
                for(int j=0;j<cutNumber;++j){
                    BufferedImage cut=source.getSubimage(j*width, i*height,  width, height);
                    Integer num = i * cutNumber + j;
                    String saveName = fileName + "_" + num;
                    File saveFile = new File("/tmp/puzzle/" +saveName);
                    ImageIO.write(cut, "JPEG", saveFile);
                    QiniuUtil.upload(saveFile, saveName);
                    boolean delete = saveFile.delete();
                }
            }
        } catch (Exception e){
            logger.error("切割图片出错: " + e.getMessage());
            e.printStackTrace();
            return -1;
        }
        return 0;
    }
}
